//
//  CityViewController.m
//  MyMovie
//
//  Created by Weiwei on 16/2/27.
//  Copyright © 2016年 bever贝沃汇力 weiwei. All rights reserved.
//

#import "CityViewController.h"
#import "CityModel.h"
@interface CityViewController (){
    NSMutableDictionary* _citiesDic;//这里面存放的是a-z和最热门、最近的城市数组
    NSMutableArray* _hotCities;//热门城市
    NSMutableArray* _latesCities;//最近城市数组
    NSMutableArray* _allKeys;//原本有多少组
    NSArray* _newAllKeys;//用来记录当前有多少组
    
}

@end

@implementation CityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self _loadData];
    
    //注册单元格
    [_cityCollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"city_cell"];
#pragma -mark目标一注册头试图
    [_cityCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"city_header"];
    
    NSArray* array1 =[[_citiesDic allKeys]sortedArrayUsingSelector:@selector(compare:)];
    _allKeys = [NSMutableArray arrayWithArray:array1];

    //发现两个汉字的数组被分配到最下面
    //（1）首先将热门数组提到最上边
    //将热门插入到第一个
    [_allKeys insertObject:[_allKeys lastObject] atIndex:0];
    //删除最后一个热门数组，最后一个就变成最近
    [_allKeys removeLastObject];
    
    //将最近插入到第二个位置
    [_allKeys insertObject:[_allKeys lastObject] atIndex:1];
    //在删除位置最后的最近数组
    [_allKeys removeLastObject];
    
#pragma -mark 最后一步
    _newAllKeys = _allKeys;
    
#pragma -mark 步骤一 增加接受通知的能力
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(valueChange) name:UITextFieldTextDidChangeNotification object:nil];
}

-(void)valueChange{
    
    //1.获取输入框的当前值
    NSString* textString = _textFiled.text;
//    NSLog(@"%@",textString);
    
    //2.创建谓词搜索条件
    NSString* string = [NSString stringWithFormat:@"self like [C] '*%@*'",textString];
    
    NSPredicate* predicate = [NSPredicate predicateWithFormat:string];
    
    //3.通过谓词进行过滤
     _newAllKeys = [_allKeys filteredArrayUsingPredicate:predicate];
    //4.刷新数据
    [_cityCollectionView reloadData];
    
    
}





//---------------加载数据----------------
-(void)_loadData{
    
    //--------这个可不是我们做的第一部------
    //这里面存放的是a-z和最热门、最近的城市数组
    _citiesDic = [[NSMutableDictionary alloc]initWithCapacity:1];
    _hotCities = [[NSMutableArray alloc]initWithCapacity:1];
    _latesCities = [[NSMutableArray alloc]initWithCapacity:1];
    
    
    //--------------------------------
    //1.通过josn文件名和DataParser获得根数据结构
    NSDictionary* rootDataDic =[DataParser jsonObjectFromFileName:@"cities"];
    
    //2.获得根数据结构，取出字典中的城市字典
    NSDictionary* inforDic = [rootDataDic objectForKey:@"infor"];
    //继续取出infoDic里的所有城市数组
    NSArray* listItemsArray = [inforDic objectForKey:@"listItems"];
    
    //3.便利城市数组，取出一个个dic，将数据存入到model里
    for (NSDictionary* dic in listItemsArray) {
        
        //取出字典，存入到model
        CityModel* model = [[CityModel alloc]initWithDic:dic];
       //进行分组存放 a-z charindex
       
#pragma -mark 非常精彩
        //(1)取出model的首字母数组
     NSMutableArray* cityArray = [_citiesDic objectForKey:model.charindex];
        //(2)判断该数组存不存在
        if (cityArray == nil) {
            //说明该数组不存在,那么创建该数组
            cityArray = [[NSMutableArray alloc]initWithCapacity:1];
            //增加对象
            [cityArray addObject:model];
            //往字典中存该数组
            [_citiesDic setObject:cityArray forKey:model.charindex];
            
        }else{
            
            //存在
            [cityArray addObject:model];
            //更新字典
            [_citiesDic setObject:cityArray forKey:model.charindex];
            
            
        }
        
        //------------是否为热门城市判断--------
        //创建一个热门城市分组_hotCities
        
        if ([model.level isEqualToString:@"1"]) {
            //加到数组中
            [_hotCities addObject:model];
            
        }
        
        //最近城市判断
        if ([model.nodepath isEqualToString:@"0"]) {
            [_latesCities addObject:model];
        }
        
        
        [_citiesDic setObject:_hotCities forKey:@"热门城市"];
        [_citiesDic setObject:_latesCities forKey:@"最近城市"];
        
        
        
        
    }
    
    
    
    
    
}

//-------------------定制头试图-------------
-(UICollectionReusableView*)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    
    if (kind == UICollectionElementKindSectionHeader) {
        //1.复用池产生一个uiView
        UICollectionReusableView* headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"city_header" forIndexPath:indexPath];
        //2.设置透明
        headerView.backgroundColor = [UIColor clearColor];
        
        
        //3.考虑复用，lable重叠问题
        for (UIView* view in headerView.subviews) {
            [view removeFromSuperview];
        }
        

        UILabel* lable = [[UILabel alloc]initWithFrame:headerView.bounds];
        lable.font = [UIFont systemFontOfSize:20];
        lable.backgroundColor = [UIColor clearColor];
        [headerView addSubview:lable];
        
        
        //4.数据的添加
        lable.text = [_newAllKeys objectAtIndex:indexPath.section];
        
        
        return headerView;
        
    }
    
    return nil;
    
    
}


//---------------------------------------------

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//---------------UICollectionView------
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
//    return 30;
    
    //获取当前的组
    NSArray* array = [_citiesDic objectForKey:_newAllKeys[section]];
    return array.count;
    
    
    
}
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    
    UICollectionViewCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"city_cell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor cyanColor];
    cell.layer.cornerRadius = 10;
    cell.layer.borderColor = [UIColor grayColor].CGColor;
    cell.layer.borderWidth = 3.0;
    
    //-------解决复用产生的lable累积问题-----
    for (UIView* view in cell.contentView.subviews) {
           
        [view removeFromSuperview];
    }
    
    
    
    //-------cell.contentView上加一个lable----
    
    
    UILabel* lable = [[UILabel alloc]initWithFrame:cell.bounds];
    lable.backgroundColor = [UIColor clearColor];
    lable.textAlignment = NSTextAlignmentCenter;
    lable.textColor = [UIColor whiteColor];
    lable.font = [UIFont systemFontOfSize:20];
//    lable.text = @"青岛";
    [cell.contentView addSubview:lable];
    
    //-------CELL通过model获取数据----
    //取出当前的model所在的组
   NSArray* array = [_citiesDic objectForKey:_newAllKeys[indexPath.section]];
    //获得model
    CityModel* model = [array objectAtIndex:indexPath.row];
    lable.text = model.name;
    
    
    
    return cell;
    
    
    
}

//设置多少组
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    
//    return _citiesDic.count;
    return _newAllKeys.count;
}

#pragma -mark目标一 实现cell的点击和返回上一页
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
//    NSLog(@"%@",indexPath);
    
    //1.返回上一页
    [self.navigationController popViewControllerAnimated:YES];
    
    //2.block传值回调
    //1.获得是哪一个组
    NSArray* array = [_citiesDic objectForKey:_newAllKeys[indexPath.section ]];
    //2.获得该cell的model
    CityModel* model = [array objectAtIndex:indexPath.row];
    
    
    //回调block
    _block(model.name);
    
    
    
    
}
#pragma -mark实现chuanzhi方法
-(void)chuanzhi:(MyBlock)block{
    _block = block;
}



@end
